import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import "./index.scss";
import { Input, Button, Table, message, Modal, Tree, Tag } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import { text_check, post_axios } from "../../utils";
import UserTable from "../../modules/userTable/index";

export default function Organization(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const [treeHeight, setTreeHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const { confirm } = Modal;
  // 国内国外判断
  const session_company = sessionStorage.getItem("company");

  const [organization_list, setOrganization_list] = useState([]);
  const [expanded_array, setExpandedArray] = useState([]);
  const getData = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    setSpinning(true);
    let res = await post_axios("admin_oneself", "m_query_all", upMsg);
    setSpinning(false);
    if (!res) return;
    let rows = res.data_rows.rows;
    let expanded_array = rows[0].child.map((item) => {
      return item.org_id;
    });
    setOrganization_list(rows);
    setExpandedArray(expanded_array);
  };

  const search_data = async () => {
    setClicked_comId("");
    setClicked_comObj({});
    getData();
  };

  // 组织列表点击
  const [clicked_comId, setClicked_comId] = useState("");
  const [clicked_comObj, setClicked_comObj] = useState({});
  const organization_row_click = (row) => {
    setClicked_comId(row.org_id);
    setClicked_comObj(row);
    get_organization_user_data(row);
  };

  // 组织-用户筛查询
  const [user_list, setUser_list] = useState([]);
  // 获取组织列表
  const get_organization_user_data = async (item) => {
    let upMsg = {
      com_id: item ? item.org_id : clicked_comId,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("organization_structure", "m_query_user", upMsg);
    setSpinning(false);
    if (!res) return;
    setUser_list(res.data_rows.rows);
  };

  // 添加组织
  const [add_com_show, setAdd_com_show] = useState(false);
  const [add_com_name, setAdd_com_name] = useState("");
  const add_com_dialog_show = () => {
    if (clicked_comId === "") {
      message.warning({
        content: t("system_manager.choose_one_organization"),
      });
      return;
    }
    setAdd_com_name("");
    setAdd_com_show(true);
  };
  const add_com_confirm = async () => {
    if (add_com_name === "") {
      message.warning({
        content: t("system_manager.enter_peer_name"),
      });
      return;
    }

    let upMsg = {
      com_id: clicked_comId,
      com: add_com_name,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true)
    let res = await post_axios("organization_structure", "m_add", upMsg);
    setSpinning(false)
    if (!res) return;
    message.success({
      content: t("common.add_scuuess"),
    });
    setAdd_com_show(false);
    setUser_list([]);
    getData();
  };

  // 修改组织
  const [change_com_show, setChange_com_show] = useState(false);
  const [change_com_name, setChange_com_name] = useState("");
  const change_com_dialog_show = () => {
    if (clicked_comId === "") {
      message.warning({
        content: t("system_manager.choose_one_organization"),
      });
      return;
    }
    let item = JSON.parse(JSON.stringify(clicked_comObj));
    setChange_com_name(item.org_name);
    setChange_com_show(true);
  };
  const change_com_confirm = async () => {
    if (change_com_name === "") {
      message.warning({
        content: t("system_manager.enter_peer_name"),
        type: "warning",
      });
      return;
    }

    let upMsg = {
      com_id: clicked_comId,
      com: change_com_name,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true)
    let res = await post_axios("organization_structure", "m_modify", upMsg);
    setSpinning(false)
    if (!res) return;
    message.success({
      content: t("common.change_success"),
    });

    setChange_com_show(false);
    search_data();
  };

  const delete_com = () => {
    if (clicked_comId === "") {
      message.warning({
        content: t("system_manager.choose_one_organization"),
        type: "warning",
      });
      return;
    }
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: <p>{t("system_manager.sure_to_delete")}</p>,
      onOk: async () => {
        let upMsg = {
          com_id: clicked_comId,
          com: clicked_comObj.org_name,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        setSpinning(true)
        let res = await post_axios("organization_structure", "m_del", upMsg);
        setSpinning(false)
        if (!res) return;
        message.warning({
          content: t("common.delete_success"),
          type: "success",
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  function gradeItem(nodeData) {
    switch (nodeData.org_grade) {
      case "1":
        return <Tag color="#2db7f5">{t("system_manager.level1")}</Tag>;
      case "2":
        return <Tag color="#2db7f5">{t("system_manager.level2")}</Tag>;
      case "3":
        return <Tag color="#2db7f5">{t("system_manager.level3")}</Tag>;
      case "4":
        return <Tag color="#2db7f5">{t("system_manager.level4")}</Tag>;
      case "5":
        return <Tag color="#2db7f5">商户</Tag>;
      case "6":
        return <Tag color="#2db7f5">项目</Tag>;
      case "7":
        return <Tag color="#2db7f5">点位</Tag>;
      default:
        return "";
    }
  }
  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight = document.getElementsByClassName(
        "organization_structure"
      )[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 30;
      const treeHeight = tabBoxHeight - 42 - 30;
      setTableHeight(tableHeight);
      setTreeHeight(treeHeight);
    });
  }, []);
  return (
    <>
      <div className="organization_structure modules">
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={add_com_dialog_show}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={change_com_dialog_show}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_com}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>

        <div className="table_box">
          <div className="tree_box">
            {treeHeight !== 0 ? (
              <Tree
                showLine
                switcherIcon={<DownOutlined />}
                defaultExpandedKeys={expanded_array}
                treeData={organization_list}
                height={treeHeight}
                fieldNames={{
                  title: "org_name",
                  key: "org_id",
                  children: "child",
                }}
                blockNode
                titleRender={(nodeData) => {
                  return (
                    <p key={nodeData.org_id}>
                      <span style={{ marginRight: "10px" }}>
                        {nodeData.org_name}
                      </span>
                      {gradeItem(nodeData)}
                    </p>
                  );
                }}
                onSelect={(_, e) => {
                  const { node } = e;
                  return organization_row_click(node);
                }}
              />
            ) : (
              <div className="loading_modules">模块加载中...</div>
            )}
          </div>
          <div className="org_user_box noPage-table">
            <UserTable user_list={user_list} tableHeight={tableHeight} />
          </div>
        </div>
      </div>

      <Modal
        title={t("common.add") + t("system_manager.organization")}
        open={add_com_show}
        onOk={add_com_confirm}
        onCancel={() => setAdd_com_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">
            {t("system_manager.superior_name")}
          </div>
          <Input defaultValue={clicked_comObj.org_name} />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">
            {t("platform_manager.company_name")}
          </div>
          <Input
            placeholder=" "
            value={add_com_name}
            onChange={(e) => setAdd_com_name(e.target.value)}
          />
        </div>
      </Modal>

      <Modal
        title={t("common.change") + t("system_manager.organization")}
        open={change_com_show}
        onOk={change_com_confirm}
        onCancel={() => setChange_com_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("system_manager.peer_name")}</div>
          <Input
            placeholder=" "
            value={change_com_name}
            onChange={(e) => setChange_com_name(e.target.value)}
          />
        </div>
      </Modal>
    </>
  );
}
